package com.shipwe.loans.utils.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.shipwe.adapter.ShipweOnItemChildClickListener
import com.shipwe.adapter.ShipweRecyclerViewAdapter
import com.shipwe.adapter.ShipweViewHolderHelper
import com.shipwe.loans.MyApps
import com.shipwe.loans.R
import com.shipwe.loans.databinding.DialogBirthdayBinding
import com.shipwe.loans.pro.ShipweDialog
import com.shipwe.loans.utils.AppDensityUtil
import com.shipwe.loans.utils.ShipweToastManager
import com.shipwe.loans.utils.decoration.GridSpacingItemDecoration
import com.shipwe.loans.utils.event.AppEventPointHelper
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.helper.ShipweDateHelper
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Calendar

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/19 13:54
 * @Annotation：流程选择出生日期
 */
class BirthdayDialog : ShipweDialog {
    private lateinit var binding: DialogBirthdayBinding
    private var mCallback: IDialogCallback? = null
    //开始选择时间
    private var startTime = 0L;

    //事件备注
    private var eventRemark = ""

    /* 日期 */
    private var mDayAdapter: DayAdapter? = null

    //年
    private var showYear = ShipweDateHelper.getCurtYear()

    //月
    private var showMonth = ShipweDateHelper.getCurtMonth()

    //日
    private var showDay = ShipweDateHelper.getCurtDay()

    constructor(context: Context) : super(context) {}
    constructor(context: Context, callback: IDialogCallback?) : super(context) {
        mCallback = callback
    }

    constructor(context: Context, remark: String, callback: IDialogCallback?) : super(context) {
        mCallback = callback
        eventRemark = remark
    }

    /**
     * 设置点击回调
     */
    fun setOnClick(callback: IDialogCallback) {
        this.mCallback = callback
    }

    override fun initWindow() {
        val params = window!!.attributes
        params.width = MyApps.app.getPhoneWidth()
        params.height = WindowManager.LayoutParams.WRAP_CONTENT
        window!!.attributes = params
        window!!.setWindowAnimations(R.style.dialog_slide_anim) //修改动画样式
        window!!.setGravity(Gravity.BOTTOM)
    }

    override fun getRootView(): View {
        binding = DialogBirthdayBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initView() {
        initWeekListView()
        initDaysListView()
    }

    override fun initListener() {
        setOnClickListener(binding.birthdayConfirm)
        //上一年
        binding.lastYear.setOnClickListener {
            showYear = ShipweDateHelper.getLastYear(showYear).get(Calendar.YEAR)
            showYear()
            showDay()
        }
        //下一年
        binding.nextYear.setOnClickListener {
            showYear = ShipweDateHelper.getNextYear(showYear).get(Calendar.YEAR)
            showYear()
            showDay()
        }

        //上一月
        binding.lastMonth.setOnClickListener {
            val calendar = ShipweDateHelper.getLastMonth(showYear, showMonth)
            showYear = calendar.get(Calendar.YEAR)
            showMonth = calendar.get(Calendar.MONTH) + 1
            showYear()
            showMonth()
            showDay()
        }

        //下一月
        binding.nextMonth.setOnClickListener {
            val calendar = ShipweDateHelper.getNextMonth(showYear, showMonth)
            showYear = calendar.get(Calendar.YEAR)
            showMonth = calendar.get(Calendar.MONTH) + 1
            showYear()
            showMonth()
            showDay()
        }
    }

    override fun initData() {
        showYear()
        showMonth()
        showDay()
    }

    @SuppressLint("SimpleDateFormat")
    override fun onViewClick(v: View?) {
        when (v!!.id) {
            R.id.birthdayConfirm -> {//提交
                val selectDay = getSelectDay()
                if (selectDay == 0) {
                    ShipweToastManager.showShortText(context, context.getString(R.string.dialog_tips_select_birth_error))
                    return
                }
                dismiss()
                var formatDay = "$selectDay"
                if (selectDay < 10) {
                    formatDay = "0$selectDay"
                }

                val calendar = Calendar.getInstance()
                calendar.set(Calendar.YEAR, showYear)
                calendar.set(Calendar.MONTH, showMonth - 1)
                calendar.set(Calendar.DAY_OF_MONTH, selectDay)
                val obj = JSONObject()
                obj.put("timeInMillis", calendar.timeInMillis)
                obj.put("showDate", "$formatDay-${ShipweDateHelper.getMonthList()[showMonth - 1].optString("month")}-$showYear")
                obj.put("subDate", SimpleDateFormat("yyyy-MM-dd").format(calendar.timeInMillis))
                obj.put("duration",System.currentTimeMillis() - startTime)
                if (mCallback != null) {
                    mCallback!!.completed(obj)
                }
            }
        }
    }

    override fun show() {
        super.show()
        startTime = System.currentTimeMillis()
    }

    interface IDialogCallback {
        fun completed(selectDate: JSONObject)
    }

    /**
     * 设置月份
     */
    private fun initWeekListView() {
        binding.weekListView.setHasFixedSize(true)
        binding.weekListView.isNestedScrollingEnabled = false
        binding.weekListView.isFocusableInTouchMode = false //不需要焦点
        val decoration = AppDensityUtil.dp2px(12f)
        binding.weekListView.addItemDecoration(GridSpacingItemDecoration(7, decoration, true))
        val layoutManager = GridLayoutManager(context, 7)
        binding.weekListView.layoutManager = layoutManager
        val weekAdapter = WeekAdapter(binding.weekListView)
        binding.weekListView.adapter = weekAdapter
        binding.weekListView.itemAnimator = DefaultItemAnimator()
        weekAdapter.data = ShipweDateHelper.getWeekList()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initDaysListView() {
        binding.daysListView.setHasFixedSize(true)
        binding.daysListView.isNestedScrollingEnabled = false
        binding.daysListView.isFocusableInTouchMode = false //不需要焦点
        val decoration = AppDensityUtil.dp2px(12f)
        binding.daysListView.addItemDecoration(GridSpacingItemDecoration(7, decoration, true))
        val layoutManager = GridLayoutManager(context, 7)
        binding.daysListView.layoutManager = layoutManager
        mDayAdapter = DayAdapter(binding.daysListView)
        binding.daysListView.adapter = mDayAdapter
        binding.daysListView.itemAnimator = DefaultItemAnimator()
        mDayAdapter!!.setOnItemChildClickListener(ShipweOnItemChildClickListener { _, _, position ->
            val item = mDayAdapter!!.getItem(position)
            if (item.optBoolean("isSelect") || item.optInt("day") == 0) {
                return@ShipweOnItemChildClickListener
            }
            for (i in 0..<mDayAdapter!!.itemCount) {
                val obj = mDayAdapter!!.getItem(i)
                obj.put("isSelect", false)
                if (i == position) {
                    obj.put("isSelect", true)
                }
            }
            mDayAdapter!!.notifyDataSetChanged()
        })
    }

    /**
     * 设置年份
     */
    private fun showYear() {
        binding.curtYear.text = "$showYear"
    }

    /**
     * 设置月份
     */
    private fun showMonth() {
        val month = ShipweDateHelper.getMonthList()[showMonth - 1]
        binding.curtMonth.text = month.optString("month")
    }

    /**
     * 设置日期
     */
    private fun showDay() {
        val dayList = arrayListOf<JSONObject>()
        //指定年月的1号是星期几
        val week = ShipweDateHelper.getDayOfWeek(showYear, showMonth, 1)
        for (i in 0..<week) {
            val item = JSONObject()
            item.put("year", 0)
            item.put("month", 0)
            item.put("day", 0)
            dayList.add(item)
        }
        dayList.addAll(ShipweDateHelper.getDayList(showYear, showMonth))
        for (i in 0..<dayList.size) {
            val day = dayList[i]
            day.put("isSelect", false)
            if (showYear == ShipweDateHelper.getCurtYear() && showMonth == ShipweDateHelper.getCurtMonth() && day.optInt(
                    "day"
                ) == showDay
            ) {
                day.put("isSelect", true)
            }
        }
        mDayAdapter!!.data = dayList
    }

    /**
     * 获取选中的日期
     */
    private fun getSelectDay(): Int {
        var day = 0
        for (i in 0..<mDayAdapter!!.itemCount) {
            val item = mDayAdapter!!.getItem(i)
            if (item.optBoolean("isSelect")) {
                day = item.optInt("day")
                break
            }
        }
        return day
    }

    /**
     * 周
     */
    internal inner class WeekAdapter(recyclerView: RecyclerView?) : ShipweRecyclerViewAdapter<String>(recyclerView, R.layout.dialog_birthday_week_item) {
        override fun fillData(helper: ShipweViewHolderHelper, position: Int, model: String) {
            helper.setText(R.id.textWeek, model)
        }
    }

    /**
     * 日期
     */
    internal inner class DayAdapter(recyclerView: RecyclerView?) :
        ShipweRecyclerViewAdapter<JSONObject>(recyclerView, R.layout.dialog_birthday_day_item) {
        override fun setItemChildListener(helper: ShipweViewHolderHelper, viewType: Int) {
            helper.setItemChildClickListener(R.id.day) //点击Item
        }

        override fun fillData(helper: ShipweViewHolderHelper, position: Int, model: JSONObject) {
            val textDay = helper.getTextView(R.id.day)
            val showDay = model.optInt("day")
            if (showDay == 0) {
                textDay.text = ""
            } else {
                textDay.text = "$showDay"
            }

            if (model.optBoolean("isSelect")) {
                textDay.setTextColor(Color.parseColor("#FFFFFFFF"))
                textDay.setBackgroundResource(R.drawable.circle_ff7543ff)
            } else {
                textDay.setTextColor(Color.parseColor("#0F2552"))
                textDay.setBackgroundColor(Color.parseColor("#00000000"))
            }
        }
    }

    override fun onStart() {
        super.onStart()
        AppEventPointHelper.appEventPointRequestAction(AppEventPointType.DIALOG.SHIPWE_DIALOG_BIRTHDAY_SHOW, eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        AppEventPointHelper.appEventPointRequestAction(AppEventPointType.DIALOG.SHIPWE_DIALOG_BIRTHDAY_DISMISS, eventRemark)
    }
}